﻿using DAL;
using DAL.DBManagers;
using System;
using System.Web.UI;
using DAL.Models;

public partial class CurrencyEdit : System.Web.UI.Page
{
    Guid CurrencyID = Guid.Empty;
    CurrenciesManager manager = new CurrenciesManager();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Guid.TryParse(Request.QueryString["id"], out CurrencyID))
        {
            if (!IsPostBack)
            {
                var curr = manager.Single(s => s.CurrencyID == CurrencyID);

                txtCurrency.Text = String.Format(Resources.Global.DecimalFormat, curr.Currency1);
                ddlCurrTypes.SelectedValue = curr.CurrencyTypeID.ToString();
                txtCurrDate.DateValue = curr.CurrencyDate;
            }
        }
        else
        {
            txtCurrDate.DateValue = DateTime.Now;
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        Page.Validate();
        if (Page.IsValid)
        {
            var user = Session["User"] as UserHelper;

            if (CurrencyID == Guid.Empty)
            {
                var currency = manager.SingleOrDefault(s => s.IsActive && s.CurrencyDate == txtCurrDate.DateValue.Value && s.CurrencyTypeID == Guid.Parse(ddlCurrTypes.SelectedValue));

                if (currency != null)
                {
                    currency.IsActive = false;

                    currency.LastModifyDate = DateTime.Now;
                    currency.LastModifier = user.UserID;
                }

                manager.Add(new Currency
                {
                    CurrencyID = Guid.NewGuid(),
                    Currency1 = decimal.Parse(txtCurrency.Text),
                    //CurrencyDate = DateTime.ParseExact(txtCurrDate.Text, "mm/dd/yyyy", null),
                    //ზევითას მაგივრად ქვემოთას ვიყენებთ.
                    CurrencyDate = txtCurrDate.DateValue.Value,
                    CurrencyTypeID = Guid.Parse(ddlCurrTypes.SelectedValue),
                    IsActive = true,
                    CreateDate = DateTime.Now,
                    CreatedBy = user.UserID
                });
            }
            else
            {
                var currency = manager.Single(s => s.CurrencyID == CurrencyID);

                currency.Currency1 = decimal.Parse(txtCurrency.Text);
                //currency.CurrencyDate = DateTime.ParseExact(txtCurrDate.Text, "mm/dd/yyyy", null);
                //ზევითას მაგივრად ქვემოთას ვიყენებთ.
                currency.CurrencyDate = txtCurrDate.DateValue.Value;
                currency.CurrencyTypeID = Guid.Parse(ddlCurrTypes.SelectedValue);
                currency.LastModifyDate = DateTime.Now;
                currency.LastModifier = user.UserID;
            }
            manager.SaveChanges();
        }
        Response.Redirect("currencyview.aspx");
    }
}